import React, { Component } from 'react';
import {render} from 'react-dom';
import AppHead from './components/AppHead/AppHead';
import Browser from './components/Browser/Browser';
import LeftDrawer from './components/LeftDrawer/LeftDrawer';
import FloatingActionButtonZoom from './components/Button/FloatingActionButtonZoom';
import SimpleBottomNavigation from './components/BottomNavigation/SimpleBottomNavigation';
import BrowserContainer from './components/Browser/BrowserContainer';


class App extends Component {
    constructor(props){
        super(props);
        this.state = {showDrawer:false,
                        browserList:[
                          ],
                        newTab:{
                            browserId:"+",
                            webaddress:"http://localhost:8080/pages/aboutblank.html"
                        },
                        browserController:{
                            webaddressInput:'',
                            currentTab:-1,
                            prevTabList:''
                        },
                        homeUlr:"https://www.baidu.com",
                        helpUlr:"http://localhost:8080/pages/help.html",
                        accountUrl:"http://localhost:8080/pages/account.html"
                    };
    }
    showLeftDrawer(){
        if(this.state.showDrawer){
            this.setState({showDrawer:false});
            console.log('showDrawer:false');
        }else{
            this.setState({showDrawer:true});
            console.log('showDrawer:true');
        }
    }
    //webview挂到页面后加载url页面。
    WebviewUpdate(){
        //获取当前的浏览器标签页，并获得dom
        let ct = this.state.browserController.currentTab;
        console.log('currentTab is :'+ct);
        let webviews = document.getElementsByTagName("webview");
        console.log(webviews[ct]);
        console.log(webviews);
        //在当前标签页中加载页面
        webviews[ct].loadURL(this.state.browserList[ct].webaddress);
    }
    goBack(){
        console.log('browser to go back.');
        let ct = this.state.browserController.currentTab;
        let webviews = document.getElementsByTagName("webview");
        console.log(webviews[ct]);
        webviews[ct].goBack();
    }
    goForward(){
        console.log('browser to go forward.');
        let ct = this.state.browserController.currentTab;
        let webviews = document.getElementsByTagName("webview");
        console.log(webviews[ct]);
        webviews[ct].goForward();
    }
    goReload(){
        console.log('browser to goReload.');
        let ct = this.state.browserController.currentTab;
        let webviews = document.getElementsByTagName("webview");
        console.log(webviews[ct]);
        webviews[ct].reload();
    }
    goHome(){
        console.log('browser to go home.');
        //更新浏览器列表
        let browserNum = -1;//记录浏览器数量
        if(this.state.browserList.length == 0){
            //只有一个 + 页
            browserNum = 0;
            console.log('当前没有打开页面.');
        }else{
            //除了+ ，还开了 browserNum个浏览器标签,
            browserNum = this.state.browserList.length;
            console.log('当前打开页面数量为：'+ browserNum);
        }
        if(this.state.browserController.currentTab == -1){
            //在 + 标签页跳转，需要增加一个新的 + 页面。
            let updateBrowserList = this.state.browserList.concat(
                {
                    browserId: browserNum,
                    webaddress: this.state.homeUlr
                });
            let updateBrowserController = Object.assign({},this.state.browserController,{currentTab:browserNum})
            this.setState({
                            browserList: updateBrowserList,
                            browserController: updateBrowserController
                        });
        }else{
            let ct = this.state.browserController.currentTab;
            let webviews = document.getElementsByTagName("webview");
            console.log(webviews[ct]);
            webviews[ct].loadURL(this.state.homeUlr);
        }

    }
    markFavorite(){
        console.log('mark as favorite.');
    }
    goTo(){
        console.log('go to url.');
        //获得地址输入栏的值
        let webaddressInputBarValue = document.getElementById('webaddressInputBar').value;

        //更新浏览器列表
        let browserNum = -1;//记录浏览器数量
        if(this.state.browserList.length == 0){
            //只有一个 + 页
            browserNum = 0;
            console.log('当前没有打开页面.');
        }else{
            //除了+ ，还开了 browserNum个浏览器标签,
            browserNum = this.state.browserList.length;
            console.log('当前打开页面数量为：'+ browserNum);
        }

        //如果处于最后一个“+”浏览器时点击“转到”按钮
        if(this.state.browserController.currentTab == -1){

            let updateBrowserController = Object.assign({},this.state.browserController,{currentTab: browserNum});
            this.setState({
                browserController: updateBrowserController
            });
            //添加一个新标签，导航到目标地址
            let updateBrowserList = this.state.browserList.concat(
                {
                    browserId: browserNum,
                    webaddress: webaddressInputBarValue
                });
            this.setState({
                            browserList: updateBrowserList
                        });

            console.log('添加新页面并跳转到新的页面地址.');
            console.log(this.state.browserController.currentTab);

        }else{
            //goto the input url.在一个已经打开某页面的（非 + 标签页）直接跳转到目标地址。
            let ct = this.state.browserController.currentTab;
            let webviews = document.getElementsByTagName("webview");
            console.log(webviews[ct]);
            webviews[ct].loadURL(webaddressInputBarValue);
            console.log('将当前页面跳转到新地址。');
        }
        /*
        setTimeout(() => {
            console.log('40 miliseconds have passed.');

        //获取当前的浏览器标签页，并获得dom
        let ct = this.state.browserController.currentTab;
        console.log(ct);
        let webviews = document.getElementsByTagName("webview");
        console.log(webviews[ct]);
        //在当前标签页中加载页面
        webviews[ct].loadURL(webaddressInputBarValue);
        }, 40);
        */

    }
    showAccount(){
        console.log('show Account.');

        //添加标签浏览器以加载account网页.默认情况，没有打开的标签页面，新建一个页面，并加载
        let browserTabId = 0;
        if(this.state.browserList.length > 0){
             //打开的浏览器标签数目，但browserId应该是最后一个标签的id加1
             browserTabId = this.state.browserList[this.state.browserList.length-1].browserId +1;
        }
        let updateBrowserList = this.state.browserList.concat(
            {
                browserId: browserTabId,
                webaddress: this.state.accountUrl
            });
        let updateBrowserController = Object.assign({},this.state.browserController,{currentTab:browserTabId});
        this.setState({
                        browserList: updateBrowserList,
                        browserController: updateBrowserController
                    });

    }
    showHelp(){
        console.log('show help.'+this.state.helpUlr);
        //添加标签浏览器以加载help网页.默认情况，没有打开的标签页面，新建一个页面，并加载
        let browserTabId = 0;
        if(this.state.browserList.length > 0){
             //打开的浏览器标签数目，但browserId应该是最后一个标签的id加1
             browserTabId = this.state.browserList[this.state.browserList.length-1].browserId +1;
        }
        let updateBrowserList = this.state.browserList.concat(
            {
                browserId: browserTabId,
                webaddress: this.state.helpUlr
            });
        let updateBrowserController = Object.assign({},this.state.browserController,{currentTab:browserTabId});
        this.setState({
                        browserList: updateBrowserList,
                        browserController: updateBrowserController
                    });
    }
    handleSelectTab(key){
        console.log('previousTab is '+ this.state.browserController.currentTab);
        let updateBrowserController = Object.assign({},this.state.browserController,{currentTab:key});
        this.setState({browserController:updateBrowserController});
        setTimeout(() => {
            console.log('currentTab is '+ this.state.browserController.currentTab);
            // 切换tab会触发地址输入栏的地址的值的变化
            this.updateWebaddressInputBar();
        }, 40);

    }
    //根据this.state.browserController.currentTab从browserList中找出index
    findIndexInBrowserList(tabid){
        //
        let tabkeys = new Array();
        for(var i=0;i<this.state.browserList.length;i++){
            tabkeys[i] = this.state.browserList[i].browserId;
        }
        return tabkeys.indexOf(tabid);
    }
    updateWebaddressInputBar(){
        let inputBar = document.getElementById('webaddressInputBar');
        if(this.state.browserController.currentTab == -1){
            inputBar.value = this.state.newTab.webaddress;
        }else{
            let index = this.findIndexInBrowserList(this.state.browserController.currentTab);
            inputBar.value = this.state.browserList[index].webaddress;
        }

    }
    handleWebaddressInput(event){
        console.log('you have input webaddress.');
        let updateBrowserController = Object.assign({},this.state.browserController,{webaddressInput:event.target.value});
        this.setState({browserController:updateBrowserController});
    }
    closeCurrentTab(){
        console.log('closeCurrentTab:'+this.state.browserController.currentTab);
        //获取browserList中的browserId组成的数组
        let tabkeys=new Array();//存放当前所有标签的tab key 的数组
        let browserListLength = 0;
        for(var i=0;i<this.state.browserList.length;i++){
            tabkeys[i] = this.state.browserList[i].browserId;
        }
        console.log("tabkeys = " + tabkeys);
        //获取需要关闭的tab的browserId
        let TabToRemove = this.state.browserController.currentTab;
        //获得需要删除的tab的index在browserList中
        let IndexOfTabToRemove = tabkeys.indexOf(TabToRemove);
        //从tabkeys中删除当前标签，然后利用数组运算出应该显示那个当前标签。
        tabkeys.splice(IndexOfTabToRemove,1);

        //计算接下来应该显示的标签
        let tabToShow = -1;//默认显示 + 页面，也就是的下面的if都不生效就会去显示 + 页面。
        if(tabkeys.length > 0){
            //用算法显示左右的标签页
            if(IndexOfTabToRemove - 1 >= 0){
                //显示左边的标签页；
                tabToShow = tabkeys[IndexOfTabToRemove - 1];
            }else{
                //显示右边的标签页
                tabToShow = tabkeys[IndexOfTabToRemove];
            }
        }

        let updateBrowserController = Object.assign({},this.state.browserController,{currentTab:tabToShow});

        //拷贝临时浏览器列表数组；
        let tempList =  new Array().concat(this.state.browserList);
        //删除当前标签浏览器；
        tempList.splice(IndexOfTabToRemove,1);
        //从列表删除元素,并更新当前页
        this.setState({
                        browserList: tempList,
                        browserController: updateBrowserController
                        });

    }
    render(){
        return (
            <div>
                <AppHead onShowDrawerClick={this.showLeftDrawer.bind(this)}
                    goBack={this.goBack.bind(this)}
                    goForward={this.goForward.bind(this)}
                    goReload={this.goReload.bind(this)}
                    goHome={this.goHome.bind(this)}
                    markFavorite={this.markFavorite.bind(this)}
                    goTo={this.goTo.bind(this)}
                    showAccount={this.showAccount.bind(this)}
                    showHelp={this.showHelp.bind(this)}
                    webaddressInput={this.state.browserController.webaddressInput}
                />
                <BrowserContainer browserList={this.state.browserList} newTab={this.state.newTab}
                    currentTab={this.state.browserController.currentTab}
                    handleSelectTab={this.handleSelectTab.bind(this)}
                    closeCurrentTab={this.closeCurrentTab.bind(this)} />
                <LeftDrawer showLeftDrawer={this.state.showDrawer} clickOrClose={this.showLeftDrawer.bind(this)} />

            </div>
        );
    }
}

render(<App />,document.getElementById('root'));